<?php
include('database.php');

$token = addslashes(@$_GET['token']);
if(!empty($token)) {
    $userGroup['group_id'] = '35140';
    if($userGroup['group_id']) {
        //$link = 'http://idvnn.com/website/reply/api.php?q=foody&rid='. $userGroup['group_id'];
        $list = getListComment('foody', $userGroup);
        $response = array(
            'result' => true,
            'data' => array(
                'list' => $list,
            )
        );
        
        echo json_encode($response);
        exit;
    } else {
        echo '{"result":"false", "msg":"User has not been activated"}';exit;
    }
} else {
    echo '{"result":"false", "msg":"System Error"}';exit;
}

function getListComment($chanel, $userGroup)
{
    if($chanel == 'foody') {
        return getCommentFoody($userGroup);
    }
}

function getCommentFoody($userGroup)
{
    //$sql = "SELECT image,username,description,date_comment FROM `group_foody_comment` WHERE point <= 5 and group_id = " . $userGroup['group_id'] . " order by time DESC limit 10";
    $sql = "SELECT image,username,description,date_comment FROM `group_foody_comment` WHERE group_id = " . $userGroup['group_id'] . " order by time DESC limit 10";
        $result = mysql_query($sql);

        if (!$result) {
            echo "Could not successfully run query ($sql) from DB: " . mysql_error();
            exit;
        }
        
        $num_rows = mysql_num_rows($result);
        $data = array();
        if($num_rows > 0) {
            $i=0;
            while ($row = mysql_fetch_assoc($result)) {
                $data[$i]["image"] = $row["image"];
                $data[$i]["username"] = $row["username"];
                $data[$i]["title"] = 'Quan Nuong Ngoi - Nguyen Trai';
                $data[$i]["des"] = myTruncate($row["description"], 100);
                $data[$i]["date_comment"] = $row["date_comment"];
                
                $i++;
            }

            mysql_free_result($result);
        } else {
            //case not data
        }

        return $data;
}

function myTruncate($string, $limit, $break=".", $pad="...")
{
  // return with no change if string is shorter than $limit
  if(strlen($string) <= $limit) return $string;

  // is $break present between $limit and the end of the string?
  if(false !== ($breakpoint = strpos($string, $break, $limit))) {
    if($breakpoint < strlen($string) - 1) {
      $string = substr($string, 0, $breakpoint) . $pad;
    }
  }

  return $string;
}